<template>
  <div class="host-detail-container">
    <!-- 返回按钮 -->
    <div class="header-bar">
      <button @click="goBack" class="back-btn">
        ← 返回仪表盘
      </button>
      <div class="auto-refresh">
        <label class="refresh-label">
          <input type="checkbox" v-model="autoRefresh" class="refresh-checkbox" />
          <span>自动刷新 ({{ refreshInterval / 1000}}秒)</span>
        </label>
        <button @click="manualRefresh" class="refresh-btn" :disabled="isLoading">
          🔄 {{ isLoading ? '刷新中...' : '立即刷新' }}
        </button>
      </div>
    </div>

    <!-- 主机基本信息卡片 -->
    <div class="host-info-card">
      <div class="info-header">
        <div class="host-title">
          <h1>{{ hostInfo.name || '加载中...' }}</h1>
          <span :class="['status-indicator', hostStatus]">
            {{ getStatusText(hostStatus) }}
          </span>
        </div>
        <div class="action-buttons">
          <button @click="collectSystemInfo" class="collect-btn" :disabled="collecting">
            {{ collecting ? '采集中...' : '🔄 采集系统信息' }}
          </button>
          <div class="last-update">
            最后更新: {{ lastUpdateTime }}
          </div>
        </div>
      </div>
      
      <div class="info-grid">
        <div class="info-item">
          <span class="info-label">🌐 IP地址</span>
          <span class="info-value">{{ hostInfo.ip || '-' }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">🔌 SSH端口</span>
          <span class="info-value">{{ hostInfo.port || 22 }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">👤 用户名</span>
          <span class="info-value">{{ hostInfo.username || '-' }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">🏷️ MAC地址</span>
          <span class="info-value">{{ hostInfo.mac_address || '-' }}</span>
        </div>
      </div>
      
      <!-- 系统信息 -->
      <div class="system-info-section" v-if="hostInfo.os_type || hostInfo.cpu_cores">
        <h3 class="section-title">📊 系统信息</h3>
        <div class="info-grid">
          <div class="info-item" v-if="hostInfo.os_type">
            <span class="info-label">💻 系统类型</span>
            <span class="info-value">{{ hostInfo.os_type }}</span>
          </div>
          <div class="info-item" v-if="hostInfo.os_version">
            <span class="info-label">📌 系统版本</span>
            <span class="info-value">{{ hostInfo.os_version }}</span>
          </div>
          <div class="info-item" v-if="hostInfo.os_kernel">
            <span class="info-label">⚙️ 内核版本</span>
            <span class="info-value">{{ hostInfo.os_kernel }}</span>
          </div>
          <div class="info-item" v-if="hostInfo.cpu_cores">
            <span class="info-label">🔢 CPU核心</span>
            <span class="info-value">{{ hostInfo.cpu_cores }} 核</span>
          </div>
          <div class="info-item" v-if="hostInfo.cpu_arch">
            <span class="info-label">🏗️ CPU架构</span>
            <span class="info-value">{{ hostInfo.cpu_arch }}</span>
          </div>
          <div class="info-item" v-if="hostInfo.cpu_model">
            <span class="info-label">🖥️ CPU型号</span>
            <span class="info-value">{{ hostInfo.cpu_model }}</span>
          </div>
          <div class="info-item" v-if="hostInfo.memory_info">
            <span class="info-label">🧠 内存信息</span>
            <span class="info-value">{{ hostInfo.memory_info }}</span>
          </div>
          <div class="info-item" v-if="hostInfo.disk_info">
            <span class="info-label">💾 磁盘信息</span>
            <span class="info-value">{{ hostInfo.disk_info }}</span>
          </div>
          <div class="info-item" v-if="hostInfo.public_ip">
            <span class="info-label">🌍 公网IP (ens33)</span>
            <span class="info-value">{{ hostInfo.public_ip }}</span>
          </div>
          <div class="info-item" v-if="hostInfo.private_ip">
            <span class="info-label">🔒 内网IP (ens37)</span>
            <span class="info-value">{{ hostInfo.private_ip }}</span>
          </div>
          <div class="info-item" v-if="hostInfo.info_collected_at">
            <span class="info-label">🕒 采集时间</span>
            <span class="info-value">{{ formatTime(hostInfo.info_collected_at) }}</span>
          </div>
        </div>
      </div>
      <div class="system-info-placeholder" v-else>
        <p>暂无系统信息，请点击"采集系统信息"按钮获取</p>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="isLoading && !monitorData" class="loading-state">
      <div class="loading-spinner"></div>
      <p>正在获取主机信息...</p>
    </div>

    <!-- 错误状态 -->
    <div v-if="error" class="error-state">
      <div class="error-icon">⚠️</div>
      <h3>{{ error }}</h3>
      <button @click="manualRefresh" class="retry-btn">重试</button>
    </div>

    <!-- 系统资源监控仪表盘 -->
    <div v-if="monitorData && !error" class="dashboard-grid">
      <!-- CPU监控卡片 -->
      <div class="monitor-card cpu-card">
        <div class="card-header">
          <h3>🖥️ CPU监控</h3>
          <span class="metric-value">{{ monitorData.cpu?.usage_percent?.toFixed(1) || 0 }}%</span>
        </div>
        
        <div class="circular-progress">
          <svg class="progress-ring" width="200" height="200">
            <circle
              class="progress-ring-bg"
              cx="100"
              cy="100"
              r="85"
            ></circle>
            <circle
              class="progress-ring-fill cpu-ring"
              cx="100"
              cy="100"
              r="85"
              :stroke-dasharray="calculateCircle(monitorData.cpu?.usage_percent || 0)"
            ></circle>
          </svg>
          <div class="progress-text">
            <div class="progress-percent">{{ monitorData.cpu?.usage_percent?.toFixed(1) || 0 }}%</div>
            <div class="progress-label">CPU使用率</div>
          </div>
        </div>

        <div class="metric-details">
          <div class="detail-item">
            <span class="detail-label">核心数</span>
            <span class="detail-value">{{ monitorData.cpu?.core_count || '-' }}</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">物理核心</span>
            <span class="detail-value">{{ monitorData.cpu?.physical_cores || '-' }}</span>
          </div>
        </div>
      </div>

      <!-- 内存监控卡片 -->
      <div class="monitor-card memory-card">
        <div class="card-header">
          <h3>💾 内存监控</h3>
          <span class="metric-value">{{ monitorData.memory?.usage_percent?.toFixed(1) || 0 }}%</span>
        </div>
        
        <div class="circular-progress">
          <svg class="progress-ring" width="200" height="200">
            <circle
              class="progress-ring-bg"
              cx="100"
              cy="100"
              r="85"
            ></circle>
            <circle
              class="progress-ring-fill memory-ring"
              cx="100"
              cy="100"
              r="85"
              :stroke-dasharray="calculateCircle(monitorData.memory?.usage_percent || 0)"
            ></circle>
          </svg>
          <div class="progress-text">
            <div class="progress-percent">{{ monitorData.memory?.usage_percent?.toFixed(1) || 0 }}%</div>
            <div class="progress-label">内存使用率</div>
          </div>
        </div>

        <div class="metric-details">
          <div class="detail-item">
            <span class="detail-label">总内存</span>
            <span class="detail-value">{{ monitorData.memory?.total_gb?.toFixed(2) || 0 }} GB</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">已用</span>
            <span class="detail-value">{{ monitorData.memory?.used_gb?.toFixed(2) || 0 }} GB</span>
          </div>
        </div>
      </div>

      <!-- 磁盘监控卡片 -->
      <div class="monitor-card disk-card">
        <div class="card-header">
          <h3>💿 磁盘监控</h3>
          <span class="metric-value">{{ monitorData.disk?.usage_percent?.toFixed(1) || 0 }}%</span>
        </div>
        
        <div class="circular-progress">
          <svg class="progress-ring" width="200" height="200">
            <circle
              class="progress-ring-bg"
              cx="100"
              cy="100"
              r="85"
            ></circle>
            <circle
              class="progress-ring-fill disk-ring"
              cx="100"
              cy="100"
              r="85"
              :stroke-dasharray="calculateCircle(monitorData.disk?.usage_percent || 0)"
            ></circle>
          </svg>
          <div class="progress-text">
            <div class="progress-percent">{{ monitorData.disk?.usage_percent?.toFixed(1) || 0 }}%</div>
            <div class="progress-label">磁盘使用率</div>
          </div>
        </div>

        <div class="metric-details">
          <div class="detail-item">
            <span class="detail-label">总容量</span>
            <span class="detail-value">{{ monitorData.disk?.total_gb?.toFixed(2) || 0 }} GB</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">已用</span>
            <span class="detail-value">{{ monitorData.disk?.used_gb?.toFixed(2) || 0 }} GB</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import api from '../services/api'

const router = useRouter()
const route = useRoute()

const hostId = ref(route.params.hostId)
const hostInfo = ref({
  name: route.query.name || '',
  ip: route.query.ip || '',
  status: route.query.status || 'unknown'
})

const monitorData = ref(null)
const isLoading = ref(false)
const error = ref(null)
const autoRefresh = ref(true)
const refreshInterval = ref(5000)
const lastUpdateTime = ref('-')
const collecting = ref(false)
let refreshTimer = null

const hostStatus = computed(() => {
  if (!monitorData.value) return hostInfo.value.status
  return 'online'
})

const goBack = () => {
  router.push('/dashboard')
}

const getStatusText = (status) => {
  const statusMap = {
    'online': '在线',
    'offline': '离线',
    'auth_failed': '认证失败',
    'ssh_error': 'SSH错误',
    'unknown': '未知'
  }
  return statusMap[status] || status
}

const calculateCircle = (percent) => {
  const radius = 85
  const circumference = 2 * Math.PI * radius
  const progress = (percent / 100) * circumference
  return `${progress} ${circumference}`
}

const fetchHostDetail = async () => {
  try {
    const response = await api.getHost(hostId.value)
    hostInfo.value = {
      ...hostInfo.value,
      ...response
    }
  } catch (err) {
    console.error('获取主机信息失败:', err)
  }
}

const fetchMonitorData = async () => {
  if (isLoading.value) return
  
  isLoading.value = true
  error.value = null
  
  try {
    const response = await api.hostInspection({ host_ids: [hostId.value] })
    
    if (response.results && response.results.length > 0) {
      const result = response.results[0]
      
      if (result.status === 'online') {
        monitorData.value = result
        error.value = null
      } else {
        error.value = result.error || '主机离线或无法连接'
      }
    }
    
    lastUpdateTime.value = new Date().toLocaleTimeString('zh-CN')
  } catch (err) {
    console.error('获取监控数据失败:', err)
    error.value = err.response?.data?.error || err.message || '获取数据失败'
  } finally {
    isLoading.value = false
  }
}

const manualRefresh = () => {
  fetchMonitorData()
}

const collectSystemInfo = async () => {
  if (collecting.value) return
  
  collecting.value = true
  
  try {
    const response = await api.collectSystemInfo(hostId.value)
    
    // 重新获取主机详情
    await fetchHostDetail()
    
    console.log('系统信息采集成功:', response.data)
  } catch (err) {
    console.error('采集系统信息失败:', err.response?.data?.error || err.message)
  } finally {
    collecting.value = false
  }
}

const formatTime = (timeStr) => {
  if (!timeStr) return '-'
  const date = new Date(timeStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const startAutoRefresh = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
  
  if (autoRefresh.value) {
    refreshTimer = setInterval(() => {
      fetchMonitorData()
    }, refreshInterval.value)
  }
}

const toggleAutoRefresh = () => {
  if (autoRefresh.value) {
    startAutoRefresh()
  } else {
    if (refreshTimer) {
      clearInterval(refreshTimer)
      refreshTimer = null
    }
  }
}

onMounted(async () => {
  await fetchHostDetail()
  await fetchMonitorData()
  
  if (autoRefresh.value) {
    startAutoRefresh()
  }
})

onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
})

watch(autoRefresh, toggleAutoRefresh)
</script>

<style scoped>
.host-detail-container {
  padding: 20px;
  max-width: 1800px;
  margin: 0 auto;
  min-height: 100vh;
}

.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  padding: 15px 20px;
  background: var(--color-bg-secondary);
  border-radius: 15px;
  box-shadow: var(--shadow-card);
}

.back-btn {
  padding: 10px 24px;
  background: linear-gradient(135deg, var(--color-accent-pink), var(--color-accent-purple));
  border: none;
  border-radius: 25px;
  color: white;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.back-btn:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-hover);
}

.auto-refresh {
  display: flex;
  align-items: center;
  gap: 15px;
}

.refresh-label {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--color-text-primary);
  font-size: 14px;
  cursor: pointer;
}

.refresh-checkbox {
  width: 18px;
  height: 18px;
  cursor: pointer;
  accent-color: var(--color-accent-pink);
}

.refresh-btn {
  padding: 8px 20px;
  background: var(--color-accent-success);
  border: none;
  border-radius: 20px;
  color: white;
  font-size: 13px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.refresh-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(81, 207, 102, 0.3);
}

.refresh-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.host-info-card {
  background: var(--color-bg-secondary);
  border-radius: 20px;
  padding: 25px;
  margin-bottom: 25px;
  box-shadow: var(--shadow-card);
  border: 2px solid var(--color-border);
}

.info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 2px solid var(--color-border);
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 15px;
}

.collect-btn {
  padding: 10px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 20px;
  color: white;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  white-space: nowrap;
}

.collect-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.collect-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.host-title {
  display: flex;
  align-items: center;
  gap: 15px;
}

.host-title h1 {
  font-size: 28px;
  color: var(--color-accent-pink);
  margin: 0;
  font-weight: 700;
}

.status-indicator {
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 13px;
  font-weight: 600;
  border: 2px solid;
}

.status-indicator.online {
  background: rgba(81, 207, 102, 0.15);
  color: var(--color-accent-success);
  border-color: var(--color-accent-success);
}

.status-indicator.offline,
.status-indicator.auth_failed,
.status-indicator.ssh_error {
  background: rgba(255, 107, 107, 0.15);
  color: #ff6b6b;
  border-color: #ff6b6b;
}

.last-update {
  color: var(--color-text-secondary);
  font-size: 13px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
  padding: 15px;
  background: var(--color-bg-primary);
  border-radius: 12px;
  border: 2px solid var(--color-border);
}

.info-label {
  color: var(--color-text-secondary);
  font-size: 13px;
  font-weight: 600;
}

.info-value {
  color: var(--color-text-primary);
  font-size: 16px;
  font-weight: 600;
  font-family: monospace;
}

.system-info-section {
  margin-top: 25px;
  padding-top: 25px;
  border-top: 2px solid var(--color-border);
}

.section-title {
  font-size: 18px;
  color: var(--color-accent-pink);
  margin-bottom: 15px;
  font-weight: 700;
}

.system-info-placeholder {
  margin-top: 25px;
  padding: 30px;
  background: rgba(255, 182, 193, 0.05);
  border: 2px dashed var(--color-border);
  border-radius: 12px;
  text-align: center;
}

.system-info-placeholder p {
  color: var(--color-text-secondary);
  font-size: 14px;
  margin: 0;
}

.loading-state,
.error-state {
  text-align: center;
  padding: 80px 20px;
}

.loading-spinner {
  width: 60px;
  height: 60px;
  border: 6px solid var(--color-border);
  border-top-color: var(--color-accent-pink);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.error-icon {
  font-size: 80px;
  margin-bottom: 20px;
}

.error-state h3 {
  color: #ff6b6b;
  margin-bottom: 20px;
}

.retry-btn {
  padding: 10px 24px;
  background: var(--color-accent-pink);
  border: none;
  border-radius: 25px;
  color: white;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.retry-btn:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-hover);
}

.dashboard-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 25px;
}

.monitor-card {
  background: var(--color-bg-secondary);
  border-radius: 20px;
  padding: 25px;
  box-shadow: var(--shadow-card);
  border: 2px solid var(--color-border);
  transition: all 0.3s;
}

.monitor-card:hover {
  transform: translateY(-5px);
  box-shadow: var(--shadow-hover);
}

.cpu-card {
  border-color: var(--color-accent-success);
}

.memory-card {
  border-color: var(--color-accent-blue);
}

.disk-card {
  border-color: var(--color-accent-orange);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 2px solid var(--color-border);
}

.card-header h3 {
  font-size: 20px;
  color: var(--color-text-primary);
  margin: 0;
  font-weight: 700;
}

.metric-value {
  font-size: 28px;
  font-weight: 700;
  background: linear-gradient(135deg, var(--color-accent-pink), var(--color-accent-purple));
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.circular-progress {
  position: relative;
  width: 200px;
  height: 200px;
  margin: 0 auto 25px;
}

.progress-ring {
  transform: rotate(-90deg);
}

.progress-ring-bg {
  fill: none;
  stroke: var(--color-bg-primary);
  stroke-width: 12;
}

.progress-ring-fill {
  fill: none;
  stroke-width: 12;
  stroke-linecap: round;
  transition: stroke-dasharray 0.5s ease;
}

.cpu-ring {
  stroke: var(--color-accent-success);
}

.memory-ring {
  stroke: var(--color-accent-blue);
}

.disk-ring {
  stroke: var(--color-accent-orange);
}

.progress-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}

.progress-percent {
  font-size: 36px;
  font-weight: 700;
  color: var(--color-text-primary);
  margin-bottom: 5px;
}

.progress-label {
  font-size: 13px;
  color: var(--color-text-secondary);
  font-weight: 600;
}

.metric-details {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: var(--color-bg-primary);
  border-radius: 10px;
  border: 2px solid var(--color-border);
}

.detail-label {
  color: var(--color-text-secondary);
  font-size: 13px;
  font-weight: 600;
}

.detail-value {
  color: var(--color-text-primary);
  font-size: 14px;
  font-weight: 700;
  font-family: monospace;
}

@media (max-width: 1200px) {
  .dashboard-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .header-bar {
    flex-direction: column;
    gap: 15px;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
}
</style>
